<template>
  <view>
    <view>
      <up-upload :fileList="fileList" @afterRead="handleAfterRead" @delete="deletePic" @clickPreview="clickPreview"
        name="1" multiple :maxCount="maxNumber" :previewFullImage="true"></up-upload>
    </view>
    <!--		<view v-else>  v-if="this.title != '车辆上传'"-->
    <!--			<up-button :customStyle="{width: '200rpx'}" type="primary" text="车辆上传" @click="navigateTo()"></up-button>-->
    <!--		</view>-->
  </view>
</template>

<script>

import {
  useUserStore
} from '@/pinia-store/user'
import { COMMON_API_BASE_URL } from '@/utils/request'
import {
  mapStores
} from 'pinia'
import componentMinxins from '../ComponentMinxins'



export default {
  mixins: [componentMinxins],
  props: {
    value: {
      type: Array,
      default: () => {
        return []
      }
    },
    placeholder: {
      type: String,
      default: '请选择图片'
    },
    maxSize: {
      type: Number,
      default: 5
    },
    maxNumber: {
      type: Number,
      default: 10
    },
    enableZip: {
      type: Boolean,
      default: true
    },
    itemIndex: {
      type: Number,
      default: 0
    },
    format: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: null
    },
    ApplyDetailList: {
      type: Array,
      default: () => {
        return []
      }
    },
    itemId: {
      type: String,
      required: true
    },
  },
  data () {
    return {
      fileList: [],
      token: '',
    }
  },
  computed: {
    ...mapStores(useUserStore)
  },
  created () {

  },
  mounted () {
    let value = uni.getStorageSync('formData');
    let formItems = JSON.parse(value.formItems);
    formItems.forEach(item => {
      if (item.title == this.title) {
        uni.removeStorageSync(`${item.id}`);
      }
    })
    this.token = this.userStore.user.token;
    this.setechodata()
  },
  watch: {
    fileList: {
      handler (newValue) {
        let value = uni.getStorageSync('formData');
        let formItems = JSON.parse(value.formItems);
        formItems.forEach(item => {
          if (item.title == this.title) {
            // item.value = newValue;
            // uni.setStorageSync(item.id, newValue);
            item.value  = newValue.map(file  => ({
              ...file,
              url: file.originalUrl  || file.url  
            }));
            uni.setStorageSync(item.id,  item.value); 
          }
        })
      },
      deep: true,
    }
  },
  methods: {
    setechodata () {
      // 添加数据回显逻辑
      if (this.ApplyDetailList && this.ApplyDetailList.formData && this.itemId) {
        // 检查 formData 中是否存在当前 itemId 对应的字段 
        if (this.ApplyDetailList.formData.hasOwnProperty(this.itemId)) {
          // 获取对应的值
          const fieldValue = this.ApplyDetailList.formData[this.itemId];

          // 如果值是数组，取第一个元素（根据你的数据结构）
          if (Array.isArray(fieldValue) && fieldValue.length > 0) {
            this.fileList = fieldValue
          } else {
            // 直接赋值 
            this.fileList = fieldValue || [];
          }
        }
      }
    },
    async handleAfterRead (e) {
      const that = this;
      e.file.forEach((item) => {
        // 先 push 到 fileList，记录当前位置
        that.fileList.push({
          ...item,
          status: "uploading",
          message: "上传中",
        });

        const currentIndex = that.fileList.length - 1; // 获取刚 push 进去的图片索引

        uni.uploadFile({
          url: `${COMMON_API_BASE_URL}/dist/interface/public/index.php/form/Form/upload`,
          filePath: item.url,
          name: 'file',
          formData: {
            'token': this.token
          },
          success: (uploadFileRes) => {
            const data = JSON.parse(uploadFileRes.data);
            // 正确设置 fileList 中刚上传的项
            that.$set(that.fileList, currentIndex, {
              url: this.ProcessingURL(data.data.url),
              id: data.data.id,
              name: data.data.name,
              status: 'success',
              message: '',
              originalUrl:data.data.url
            });
          },
          fail: () => {
            that.$set(that.fileList, currentIndex, {
              ...item,
              status: 'failed',
              message: '上传失败',
            });
          }
        });
      });

    },
    ProcessingURL (url) {
      if (url.startsWith("http://117.89.250.65:81/")) {
        url = url.replace("http://117.89.250.65:81", `${COMMON_API_BASE_URL}`);
      } else if (url.startsWith("https://cloud.mfarmers.com/")) {
        url = url.replace("https://cloud.mfarmers.com", `${COMMON_API_BASE_URL}`);
      }
      return url
    },
    deletePic (event) {
      this.fileList.splice(event.index, 1);
    },
    navigateTo (url) {
      uni.navigateTo({
        url: '/pages/apply/form/advanced/advanced'
      })
    },
    // 点击预览
    clickPreview (e) {
      uni.previewImage({
        urls: this.fileList.map(item => item.url),
        current: e.index,
      })
    }
  }
}
</script>

<style></style>
